import React, { useCallback, useMemo, } from 'react';
import { useAppStore } from '@renderer/pages/designer/store/appStore'
import CommandList from '../CommandList'
import DraggableTabs from '@renderer/components/DraggableTabs'

const EditableTabs: React.FC = () => {

  const viewItems = useAppStore((state) => state.viewItems);
  const viewActiveKey = useAppStore((state) => state.viewActiveKey);
  const setViewActiveKey = useAppStore((state) => state.actions.setViewActiveKey);
  const removeViewItem = useAppStore((state) => state.actions.removeViewItem);
  const addViewItem = useAppStore(state => state.actions.addViewItem)

  const items = useMemo(() => {
    console.log(viewItems, 'viewItems')

    return viewItems.map((item: any) => ({
      label: item.name,
      key: item.id,
      closable: true,
      children: <CommandList
        key={item.id}
        taskId={item.id}
        commands={item.commands}
      />,
      forceRender: false
    }))
  }, [viewItems])

  const onChange = useCallback((activeKey: string) => {
    setViewActiveKey(activeKey);
  }, [])

  const onEdit = useCallback((
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      addViewItem();
    } else {
      removeViewItem(targetKey as string);
    }
  }, [])

  return (
    <DraggableTabs
      className='h-full overflow-auto'
      type="editable-card"
      onChange={onChange}
      activeKey={viewActiveKey}
      onEdit={onEdit}
      items={items}
      animated
      destroyOnHidden={false}
      size='small'
      tabBarGutter={1}
    />
  );
};

export default EditableTabs;
